package org.fintan.make.master;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.fintan.make.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import io.jsonwebtoken.Claims;

@Component
public class TokenInterceptor implements HandlerInterceptor{
	
	private JWTUtil jwtUtil;
	@Autowired
	public TokenInterceptor(JWTUtil jwtUtil) {
		this.jwtUtil = jwtUtil;
	}

	//逻辑执行完毕后执行
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse reponse, Object arg2, Exception arg3)
			throws Exception {
		/*if(request.getHeader("token") == null){
			System.out.println("token 为空");
		}else{
			System.out.println(request.getHeader("token"));
		}*/
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	//请求时执行
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		// TODO Auto-generated method stub
		//添加跨域CORS
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,token");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");

		System.out.println(request.getRequestURI());
		if(request.getRequestURI().equals("/user/register") || request.getRequestURI().equals("/login"))
        {
            return true;
        }else if(request.getHeader("token") == null){
			System.out.println("token 为空");
			return false;
			
		}else{
			System.out.println(request.getHeader("token"));
			//使用验签
			String token = request.getHeader("token");
			Claims claims = jwtUtil.parseJWT(token);
			if(claims.get("userName") != null){
				return true;
			}
			return false;
		}
	}

    

}